const Service = require('egg').Service,
  moment = require('moment'),
  redisKey = require('../utils/redis_key'),
  utils = require('../utils/utils');

class OperatorService extends Service {
  async create(data) {
    let role_name;
    switch (data.idx) {
      case '9':
        role_name = '营销角色';
        break;
      case '99':
        role_name = '开发角色';
        break;
      case '999':
        role_name = '管理员';
        break;
      default:
        break;
    }

    // 是否存在username
    const isExist = await this.app.model.Operator.findOne({
      username: data.username,
    });

    if (isExist) {
      return {
        error: '用户已存在',
      };
    }

    const operator = new this.app.model.Operator({
      username: data.username,
      password: data.password,
      realname: data.realname,
      roles: [{
        idx: data.idx,
        role_name,
      }],
    });

    return await operator.save();
  }


  async login(data) {
    const operator = await this.app.model.Operator.findOne({
      username: data.username,
      password: data.password,
    });

    if (!operator) {
      return {
        error: '用户名或密码不正确',
      };
    }

    // 生成token
    const token = utils.generateToken(data.username, this.app.config.token_secret);
    // 用户信息
    const json = {
      _id: operator._id,
      username: operator.username,
      realname: operator.realname,
      roles: operator.roles,
    };
    // 存储登录信息
    const redisKeyToken = redisKey.token(token);
    await this.app.redis.set(redisKeyToken, JSON.stringify(json));
    // 设置过期时间
    const time = Math.floor(moment().add(this.app.config.token_expire_days, 'days').toDate()
      .getTime() / 1000);
    await this.app.redis.expireat(redisKeyToken, time);

    return {
      token,
      idx: operator.roles[0].idx,
    };
  }
}

module.exports = OperatorService;
